package com.chenyue.cm.match.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chenyue.cm.base.aop.Log;
import com.chenyue.cm.base.bean.Pageable;
import com.chenyue.cm.bean.Success;
import com.chenyue.cm.common.utils.RequestUtil;
import com.chenyue.cm.common.utils.StringUtils;
import com.chenyue.cm.live.domain.JdLiveRecord;
import com.chenyue.cm.live.service.JdLiveRecordService;
import com.chenyue.cm.match.dao.JdMatchItemRelationMapper;
import com.chenyue.cm.match.domain.*;
import com.chenyue.cm.match.service.JdMatchFormatService;
import com.chenyue.cm.match.service.JdMatchService;
import com.chenyue.cm.match.service.ViewMatchItemService;
import com.chenyue.cm.utils.DateUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author chenyue-cm
 * @date 2021-07-20
 */
@RestController
@RequestMapping("/jdMatch")
public class JdMatchController {

    private final JdMatchService jdMatchService;

    private final JdMatchItemRelationMapper relationMapper;

    private final JdMatchFormatService jdMatchFormatService;

    private final JdLiveRecordService jdLiveRecordService;

    private final ViewMatchItemService viewMatchItemService;

    public JdMatchController(JdMatchService jdMatchService,
                             @Qualifier("jdMatchItemRelationMapper") JdMatchItemRelationMapper relationMapper,
                             JdMatchFormatService jdMatchFormatService,
                             JdLiveRecordService jdLiveRecordService, ViewMatchItemService viewMatchItemService) {
        this.jdMatchService = jdMatchService;
        this.relationMapper = relationMapper;
        this.jdMatchFormatService = jdMatchFormatService;
        this.jdLiveRecordService = jdLiveRecordService;
        this.viewMatchItemService = viewMatchItemService;
    }

    @RequestMapping("/getList")
    public Success getList(HttpServletRequest request) {
        Pageable pageInfo = RequestUtil.getPageable(request);
        //设置分页信息
        PageHelper.startPage(pageInfo.getPageIndex(), pageInfo.getPageSize(), true);
        Map<String, Object> pageSearch = pageInfo.getPageSearch();
        LambdaQueryWrapper<JdMatch> wrapper = new LambdaQueryWrapper<>();
//        new LambdaQueryWrapper<>(jdMatchService).eq(JdMatch::getName, 1);
        if (null != pageSearch) {
            //赛事名称
            if (null != pageSearch.get("SEARCH_LIKE_name")) {
                wrapper.like(JdMatch::getName, String.valueOf(pageSearch.get("SEARCH_LIKE_name")));
            }
            //地区编码
//            if (null != pageSearch.get("SEARCH_EQ_area")) {
//                wrapper.eq(JdMatch::getProvinceCode, String.valueOf(pageSearch.get("SEARCH_EQ_area")))
//                        .or()
//                        .eq(JdMatch::getCityCode, String.valueOf(pageSearch.get("SEARCH_EQ_area")))
//                        .or()
//                        .eq(JdMatch::getAreaCode, String.valueOf(pageSearch.get("SEARCH_EQ_area")));
//            }
        }
        wrapper.eq(JdMatch::getState, 1);
        wrapper.orderByDesc(JdMatch::getCt);
        List<JdMatch> list = jdMatchService.list(wrapper);

        //封装返回结果
        PageInfo<JdMatch> result = new PageInfo<JdMatch>(list);

        return Success.success(result);
    }

    @RequestMapping("/getMatchList")
    public Success getMatchList(HttpServletRequest request) {
        //设置分页信息
        LambdaQueryWrapper<JdMatch> wrapper = new LambdaQueryWrapper<>();
        List<JdMatch> list = jdMatchService.list(wrapper);
        return Success.success(list);
    }

    /**
     * @param vo 插入实体
     * @return Success
     */
    @Log
    @RequestMapping("/save")
    public Success save(JdMatch vo, HttpServletRequest request) {
        //赛程
        String format = request.getParameter("format");
        JSONArray formatListArray = null;
        if (null != format) {
            JSONObject formatListObject = JSON.parseObject(format);
            formatListArray = (JSONArray) formatListObject.get("formatList");
            if (formatListArray.size() > 3) {
                return Success.error("最多添加3个赛程");
            }
            formatListArray.sort(Comparator.comparing(obj -> ((JSONObject) obj).getDate("startTime")));
        }
        //项目
        String itemIds = request.getParameter("itemIds");
        //直播间
        String live = request.getParameter("live");
        JSONArray liveListArray = null;
        if (null != live) {
            JSONObject liveListObject = JSON.parseObject(live);
            liveListArray = (JSONArray) liveListObject.get("liveList");
        }
        vo.setCt(DateUtils.getToday());
        //0代表后台管理员 添加
        vo.setCu(0);
        //后台管理员添加的默认审核通过
        vo.setState(1);
        vo.setIsPublic(1);
        vo.setIsCenterPush(1);
        boolean success = jdMatchService.save(vo);
        if (success) {
//        if (true) {
            String[] itemIdsStr = itemIds.split(",");
            for (String itemId : itemIdsStr) {
                if (StringUtils.isNotEmpty(itemId)) {
                    JdMatchItemRelation relation = new JdMatchItemRelation();
                    relation.setMatchId(vo.getId());
                    relation.setItemId(Integer.parseInt(itemId));
                    relationMapper.insert(relation);
                }
            }
            if (null != formatListArray && formatListArray.size() > 0) {
                //新增赛程
                int start = 0;
                if(formatListArray.size() == 1){
                    start = 3;
                }else if(formatListArray.size() == 3){
                    start = 1;
                }
                for (Object formatObject : formatListArray) {
                    JSONObject formatJsObject = (JSONObject) JSONObject.toJSON(formatObject);
                    JdMatchFormat formatInfo = new JdMatchFormat();
                    formatInfo.setMatchId(vo.getId());
                    formatInfo.setStartTime(formatJsObject.getDate("startTime"));
                    formatInfo.setEndTime(formatJsObject.getDate("endTime"));
                    formatInfo.setArrangeOrder(start++);
                    formatInfo.setPromotionNum(formatJsObject.getInteger("promotionNum"));
                    formatInfo.setPromotionScore(formatJsObject.getInteger("promotionScore"));
                    formatInfo.setUpdateType(formatJsObject.getInteger("updateType"));
                    jdMatchFormatService.save(formatInfo);
                }
            }
            if (null != liveListArray && liveListArray.size() > 0) {
                for (Object liveObject : liveListArray) {
                    JSONObject liveJsObject = (JSONObject) JSONObject.toJSON(liveObject);
                    JdLiveRecord record = new JdLiveRecord();
                    record.setMatchId(vo.getId());
                    record.setTitle(liveJsObject.getString("title"));
                    record.setLiveId(liveJsObject.getInteger("liveId"));
                    record.setLiveLogo(liveJsObject.getString("liveLogo"));
//                    record.setArrangeId(0);
//                    record.setStartTime();
//                    record.setEndTime();
                    jdLiveRecordService.save(record);
                }
            }
            return Success.success();
        } else {
            return Success.error();
        }
    }

    /**
     * @param vo      修改实体
     * @param request id
     * @return Success
     */
    @Log
    @RequestMapping("/edit")
    public Success edit(JdMatch vo, HttpServletRequest request) {
        String format = request.getParameter("format");
        //已删除的赛程
        String delFormatArray = request.getParameter("delFormatList");
        List<String> delFormatList = JSON.parseArray(delFormatArray,String.class);
        JSONArray formatListArray = null;
        if (null != format) {
            JSONObject formatListObject = JSON.parseObject(format);
            formatListArray = (JSONArray) formatListObject.get("formatList");
            if (formatListArray.size() > 3) {
                return Success.error("最多添加3个赛程");
            }
            formatListArray.sort(Comparator.comparing(obj -> ((JSONObject) obj).getDate("startTime")));
        }
        String id = request.getParameter("id");
        String itemIds = request.getParameter("itemIds");
        if (StringUtils.isNotEmpty(id)) {
            //先删除之前的关联关系
            LambdaQueryWrapper<JdMatchItemRelation> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(JdMatchItemRelation::getMatchId, id);
            relationMapper.delete(wrapper);
            //新增 关联关系
            String[] itemIdsStr = itemIds.split(",");
            for (String itemId : itemIdsStr) {
                if (StringUtils.isNotEmpty(itemId)) {
                    JdMatchItemRelation relation = new JdMatchItemRelation();
                    relation.setMatchId(vo.getId());
                    relation.setItemId(Integer.parseInt(itemId));
                    relationMapper.insert(relation);
                }
            }
            if (null != formatListArray && formatListArray.size() > 0) {
                //删除已删除得赛程和相关的liveRecord
                if(delFormatList != null && delFormatList.size() > 0){
                    //删除相关赛程
                    LambdaQueryWrapper<JdMatchFormat> formatWrapper = new LambdaQueryWrapper<>();
                    formatWrapper.eq(JdMatchFormat::getMatchId, id);
                    formatWrapper.in(JdMatchFormat::getId,delFormatList);
                    jdMatchFormatService.remove(formatWrapper);
                    //删除赛程相关的liveRecord
                    LambdaQueryWrapper<JdLiveRecord> liveRecordWrapper = new LambdaQueryWrapper<>();
                    liveRecordWrapper.eq(JdLiveRecord::getMatchId, id);
                    liveRecordWrapper.in(JdLiveRecord::getArrangeId,delFormatList);
                    jdLiveRecordService.remove(liveRecordWrapper);
                }
                //新增赛程
                int start = 0;
                if(formatListArray.size() == 1){
                    start = 3;
                }else if(formatListArray.size() == 3){
                    start = 1;
                }
                for (Object formatObject : formatListArray) {
                    JSONObject formatJsObject = (JSONObject) JSONObject.toJSON(formatObject);
                    JdMatchFormat formatInfo = new JdMatchFormat();
                    formatInfo.setMatchId(vo.getId());
                    formatInfo.setStartTime(formatJsObject.getDate("startTime"));
                    formatInfo.setEndTime(formatJsObject.getDate("endTime"));
                    formatInfo.setArrangeOrder(start++);
                    formatInfo.setPromotionNum(formatJsObject.getInteger("promotionNum"));
                    formatInfo.setPromotionScore(formatJsObject.getInteger("promotionScore"));
                    formatInfo.setUpdateType(formatJsObject.getInteger("updateType"));

                    if(formatJsObject.getInteger("id") != null){
                        formatInfo.setId(formatJsObject.getInteger("id"));
                        jdMatchFormatService.updateById(formatInfo);
                    }else{
                        jdMatchFormatService.save(formatInfo);
                    }
                }
            }
            int success = jdMatchService.getBaseMapper().updateByPrimaryKey(vo);
            return success > 0 ? Success.success() : Success.error();
        } else {
            return Success.error("id不能为空");
        }
    }

    /**
     * @param id 主键
     * @return Success
     */
    @Log
    @RequestMapping("/delete/{id}")
    public Success deleteByPrimaryKey(@PathVariable("id") Integer id) {
        JdMatchExample aExample = new JdMatchExample();
        aExample.createCriteria().andIdEqualTo(id);
        int success = jdMatchService.deleteByExample(aExample);
        //删除live_record
        LambdaQueryWrapper<JdLiveRecord> liveRecordWrapper = new LambdaQueryWrapper<>();
        liveRecordWrapper.eq(JdLiveRecord::getMatchId, id);
        boolean remove = jdLiveRecordService.remove(liveRecordWrapper);
        return success > 0 && remove ? Success.success() : Success.error();
    }

    /**
     * 【API】----  删除多个数据
     *
     * @return Success
     */
    @Log
    @RequestMapping("/delete")
    public Success delete(String ids) {
        String[] idStrings = ids.split(",");
        for (String idString : idStrings) {
            int success = jdMatchService.deleteByPrimaryKey(idString);
            if (success == 0) {
                return Success.error();
            }
        }
        return Success.success();
    }

    /**
     * 审核比赛
     *
     * @return Success
     */
    @Log
    @RequestMapping("/checkMatch")
    public Success checkMatch(HttpServletRequest request) {
        String id = request.getParameter("id");
        String state = request.getParameter("state");
        String remark = request.getParameter("remark");
        JdMatch match = jdMatchService.getById(id);
        match.setState(Integer.parseInt(state));
        match.setRemark(remark);
        int success = jdMatchService.updateByPrimaryKey(match);
        return success > 0 ? Success.success() : Success.error();
    }

    /**
     * @return success
     */
    @Log
    @RequestMapping("/getThirdMatchList")
    public Success getThirdMatchList(HttpServletRequest request) {
        Pageable pageInfo = RequestUtil.getPageable(request);
        //设置分页信息
        PageHelper.startPage(pageInfo.getPageIndex(), pageInfo.getPageSize(), true);
        QueryWrapper<JdMatch> wrapper = new QueryWrapper<>();
        wrapper.ne("state", 1);
        wrapper.eq("is_center_push", 0);
        wrapper.orderBy(true, false, "ct");
        List<JdMatch> matchList = jdMatchService.list(wrapper);
        //封装返回结果
        PageInfo<JdMatch> result = new PageInfo<JdMatch>(matchList);

        return Success.success(result);
    }

    /**
     * @return success
     */
    @Log
    @RequestMapping("/getOnMatchList")
    public Success getOnMatchList(HttpServletRequest request) {
        Pageable pageInfo = RequestUtil.getPageable(request);
        //设置分页信息
        PageHelper.startPage(pageInfo.getPageIndex(), pageInfo.getPageSize(), true);
        Map<String, Object> pageSearch = pageInfo.getPageSearch();
        QueryWrapper<ViewMatchItem> wrapper = new QueryWrapper<>();
        if (null != pageSearch) {
            //赛事名称
            if (null != pageSearch.get("SEARCH_LIKE_name")) {
                wrapper.like("name", String.valueOf(pageSearch.get("SEARCH_LIKE_name")));
            }
        }
        wrapper.eq("state", 1);
        wrapper.le("start_time", DateUtils.getToday());
        wrapper.orderByDesc("ct");
        List<ViewMatchItem> matchList = viewMatchItemService.list(wrapper);
        //封装返回结果
        PageInfo<ViewMatchItem> result = new PageInfo<ViewMatchItem>(matchList);

        return Success.success(result);
    }
}
